/* Copyright (c) 2008 Charles Rich and Worcester Polytechnic Institute.
 * All Rights Reserved.  Use is subject to license terms.  See the file
 * "license.terms" for information on usage and redistribution of this
 * file and for a DISCLAIMER OF ALL WARRANTIES.
 */
package edu.wpi.cetask;

import javax.script.*;

/**
 * Base class for instances of classes.
 */
abstract class Instance {
   
   private final TaskModel.Member type;
   
   public TaskModel.Member getType () { return type; }
   
   protected final TaskEngine engine; 
   
   Instance (TaskModel.Member type, TaskEngine engine) { 
      if ( type == null ) 
         throw new IllegalArgumentException("Type of instance cannot be null");
      this.type = type;
      this.engine = engine;
      // $id and $model are future extensions to standard
      bindings.put("$id", type.getId());
      bindings.put("$model", type.getNamespace());
   }
   
   // store slot values in JavaScript form
   protected final Bindings bindings = new SimpleBindings();
   
   protected Object eval (String expression, String where) {
      try { return engine.eval(expression, bindings, where); }
      catch (ScriptException e) { throw new RuntimeException(e); }
   }
  
   protected Object eval (String script, Bindings extra, String where) 
          throws ScriptException {
      return engine.eval(script, extra, where);
   }
   
   protected Boolean evalCondition (String expression, String where) {   
      return (Boolean) eval(expression, where);
   }
   
   @Override
   public String toString () { 
      return TaskEngine.VERBOSE ? toStringVerbose() : getType().toString();
   }
   
   protected String toStringVerbose () { 
      return TaskEngine.DEBUG ? 
         getType()+"@"+Integer.toHexString(System.identityHashCode(this))
         : getType().toString();
   }

}
